import json
from data_processing.logger import logger

info_path = 'resources/json/response_u8.json'
diff_path = 'resources/json/chart_stats_filter.json'
output_path = 'out/chosen_info.json'

output_dict = dict()


def filter(left, right):
    with open(info_path, 'r', encoding='utf-8') as info_file:
        info_datas = json.load(info_file)

    with open(diff_path, 'r', encoding='utf-8') as diff_file:
        diff_datas = json.load(diff_file)

    for info_data in info_datas:
        info_id = info_data['id']
        level = info_data.get('ds', [0, 0, 0, 0, 0])
        exp_level = level[2] if len(level) >= 4 else 0
        mas_level = level[3] if len(level) >= 4 else 0
        rem_level = level[4] if len(level) >= 5 else 0
        is_new = info_data['basic_info']['is_new']
        if ((left <= mas_level <= right) or (left <= rem_level <= right) or (
                left <= exp_level <= right)) and not is_new:
            diff_level = diff_datas.get(info_id, [0, 0])
            title = info_data['title']
            song_type = info_data['type']
            res_data = dict()
            if left <= mas_level <= right:
                mas_diff_level = diff_level['mas']
                res_data['mas_level'] = {'title': f'{title} [{song_type}] [MAS]',
                                         'level': [mas_level, mas_diff_level]}
            if left <= rem_level <= right:
                rem_diff_level = diff_level['rem']
                res_data['rem_level'] = {'title': f'{title} [{song_type}] [REM]',
                                         'level': [rem_level, rem_diff_level]}
            if left <= exp_level <= right:
                exp_diff_level = diff_level['exp']
                res_data['exp_level'] = {'title': f'{title} [{song_type}] [EXP]',
                                         'level': [exp_level, exp_diff_level]}
            output_dict[info_id] = res_data

    with open(output_path, 'w', encoding='utf-8') as output_file:
        json.dump(output_dict, output_file, indent=4, ensure_ascii=False)

    logger.info('数据筛选完成!')
